package com.demo.apparel.controller.uniapp;

import cn.hutool.json.JSONUtil;
import com.demo.apparel.common.Result;
import com.demo.apparel.dto.uniapp.MatchCreateDTO;
import com.demo.apparel.dto.uniapp.MatchPageQueryDTO;
import com.demo.apparel.entity.Match;
import com.demo.apparel.entity.Tag;
import com.demo.apparel.service.uniapp.MatchService;
import com.demo.apparel.service.uniapp.TagService;
import com.demo.apparel.vo.PageVO;
import com.fasterxml.jackson.core.JsonProcessingException;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.*;

@RestController
@RequestMapping("/wx/match")
@io.swagger.v3.oas.annotations.tags.Tag(name = "搭配接口", description = "搭配信息")
public class MatchController {

    @Autowired
    private MatchService matchService;

    @Autowired
    private TagService tagService;

    @PostMapping("/create")
    @Operation(summary = "创建搭配")
    public Result<String> createMatch(@RequestAttribute("userId") String userId,
                                      @RequestBody MatchCreateDTO dto) throws JsonProcessingException {
        String id = matchService.createMatch(userId, dto);
        return Result.success(id);
    }

    @GetMapping("/{id}")
    @Operation(summary = "获取搭配详情")
    public Result<Map<String, Object>> getMatchDetail(@PathVariable String id) throws JsonProcessingException {
        Match match = matchService.getMatchById(id);
        if (match == null) {
            return (Result<Map<String, Object>>) Result.fail("搭配不存在");
        }

        List<String> tags = matchService.parseTags(match);
        List<String> images = matchService.parseImages(match);

        Map<String, Object> data = new HashMap<>();
        data.put("id", match.getId());
        data.put("name", match.getName());
        data.put("description", match.getDescription());
        data.put("images", images);
        data.put("tags", tags);

        return Result.success(data);
    }

    @GetMapping("/list")
    @Operation(summary = "获取用户所有搭配列表")
    public Result<List<Match>> getUserMatches(@RequestAttribute("userId") String userId) {
        List<Match> matches = matchService.getMatchesByUserId(userId);
        return Result.success(matches);
    }

    @GetMapping("/tags")
    @Operation(summary = "获取所有标签列表")
    public Result<List<Tag>> getAllTags() {
        return Result.success(tagService.getAllTags());
    }

    @PostMapping(value = "/uploadImages", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @Operation(summary = "上传搭配图片")
    public Result<List<String>> uploadImages(@RequestParam("files") List<MultipartFile> files) throws IOException {
        if (files == null || files.isEmpty()) {
            return (Result<List<String>>) Result.error("500","错误");
        }

        String uploadDir = System.getProperty("user.dir") + "/match/image/";
        String urlPrefix = "/static/match/image/";
        File dir = new File(uploadDir);
        if (!dir.exists()) dir.mkdirs();

        List<String> resultList = new ArrayList<>();
        for (MultipartFile file : files) {
            String originalFilename = file.getOriginalFilename();
            String suffix = originalFilename != null && originalFilename.contains(".")
                    ? originalFilename.substring(originalFilename.lastIndexOf("."))
                    : "";
            String filename = UUID.randomUUID().toString().replace("-", "") + suffix;
            String imageUrl = urlPrefix + filename;

            file.transferTo(new File(dir, filename));
            resultList.add(imageUrl);
        }

        return Result.success(resultList);
    }

    /**
     * 分页获取当前用户搭配列表
     */
    @Operation(summary = "分页获取用户搭配列表")
    @PostMapping("/page")
    public Result<PageVO<Map<String, Object>>> getUserMatchesPage(@RequestAttribute("userId") String userId,
                                                                  @RequestBody MatchPageQueryDTO query) {
        PageVO<Match> page = matchService.getMatchesPage(userId, query);

        // 解析 images 和 tags 为数组
        List<Map<String, Object>> records = new ArrayList<>();
        for (Match match : page.getRecords()) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", match.getId());
            map.put("userId", match.getUserId());
            map.put("name", match.getName());
            map.put("description", match.getDescription());
            map.put("images", JSONUtil.toList(match.getImages(), String.class));
            map.put("tags", JSONUtil.toList(match.getTags(), String.class));
            map.put("createdTime", match.getCreatedTime());
            map.put("updatedTime", match.getUpdatedTime());

            records.add(map);
        }

        PageVO<Map<String, Object>> resultPage = new PageVO<>(records, page.getTotal(), page.getPageNum(), page.getPageSize());
        return Result.success(resultPage);
    }

    /**
     * 分页查询所有用户搭配
     */
    @PostMapping("/all")
    public Result<PageVO<Map<String, Object>>> getAllMatchesPage(@RequestBody MatchPageQueryDTO query) {
        PageVO<Match> page = matchService.getAllMatchesPage(query);

        // 将 Match 对象的 images 和 tags 字段解析成真正数组
        List<Map<String, Object>> records = new ArrayList<>();
        for (Match match : page.getRecords()) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", match.getId());
            map.put("userId", match.getUserId());
            map.put("name", match.getName());
            map.put("description", match.getDescription());
            // 使用 Hutool JSONUtil 转成 List<String>
            map.put("images", JSONUtil.toList(match.getImages(), String.class));
            map.put("tags", JSONUtil.toList(match.getTags(), String.class));
            map.put("createdTime", match.getCreatedTime());
            map.put("updatedTime", match.getUpdatedTime());

            records.add(map);
        }

        PageVO<Map<String, Object>> resultPage = new PageVO<>(records, page.getTotal(), page.getPageNum(), page.getPageSize());
        return Result.success(resultPage);
    }

}